import imConfig from '../config/index.js'
const BenderIM = {}
BenderIM.socketTask = {}

/**
 * im 连接是否连接了
 */
BenderIM.socketOpen = false



/**
 * @param {Object} userName
 * @param {Object} passWord
 * 连接websocket
 */
BenderIM.connectSocket = function(token) {
	let loginSuccess = false
	if (!BenderIM.socketOpen) {
		BenderIM.socketTask = uni.connectSocket({
			url: imConfig.webscoketType + '://' + imConfig.websocketUrl + '?token=' + token,
			complete: (res) => {
				console.log(JSON.stringify(res))
			},
			success: (res) => {
				loginSuccess = true
			}
		})
		/**
		 * @param {Object} res
		 * 监听 连接打开
		 */
		BenderIM.socketTask.onOpen(function(res) {
			BenderIM.socketOpen = true;
			// BenderIM.onSocketOpen(res)
		})
		/**
		 * @param {Object} res
		 * 监听 服务器返回的消息
		 */
		BenderIM.socketTask.onMessage(function(res) {
			if (res) {
				BenderIM.onSocketMessage(res)
			}
		})
		/**
		 * 监听 连接关闭事件
		 */
		BenderIM.socketTask.onClose(function(res) {
			BenderIM.onClose(res)
		})
		/**
		 * 监听 websocket 错误事件
		 */
		BenderIM.socketTask.onError(function(res) {
			BenderIM.onError(res)
		})
	}
	return loginSuccess
}
/**
 * 连接成功后的消息队列
 */
BenderIM.socketMsgQueue = []
/**
 * 连接开启后的操作
 */
BenderIM.onSocketOpen = function() {
	console.log('WebSocket连接已打开！');
	BenderIM.socketOpen = true;
	for (var i = 0; i < socketMsgQueue.length; i++) {
		BenderIM.sendSocketMessage(socketMsgQueue[i]);
	}
	BenderIM.socketMsgQueue = []
}

/**
 * @param {Object} msg消息
 * 发送wb 消息
 */
BenderIM.sendSocketMessage = function(msg) {
	try {
		console.log(JSON.stringify("发送的消息为" + JSON.stringify(msg)))
		if (BenderIM.socketOpen) {
			BenderIM.socketTask.send({
				data: JSON.stringify(msg),
				success: (res => {
					console.log('发送消息成功')
				}),
				fail: () => {
					console.log('发送消息失败')
				}
			})

		} else {
			BenderIM.socketMsgQueue.push(msg);
		}
	} catch (e) {
		console.log(JSON.stringify(e))
		return false
	}
	return true

}
/**
 * @param {Object} msg
 * 监听WebSocket接受到服务器的消息事件
 * 
 */


import userMock from '../mock/user.js'
import chatMock from '../mock/chat.js'
import ImStorage from '../utils/ImStorage.js'
import ImEnum from '../enums/index.js'
import store from '../store/index.js'
BenderIM.onSocketMessage = function(res) {
	console.log('收到服务器内容：' + JSON.stringify(res));
	/**
	 * jim后台还不完善 先假处理 不想高了 等超哥后台好
	 */
	/**
	 * 登陆后提示加入群组成功
	 */
	let msg = JSON.parse(res.data)
	if (msg.code === 10011) {
		let user = ImStorage.getImStorageSync(ImEnum.ImStorageEnum.loginUserInfo)
		if (user) {
			/**
			 * 设置 聊天室信息 
			 */
			if (msg.group === '100') {
				let chatroom = [{
					id: msg.group,
					name: 'JIM 朋友圈',
					nickName: 'JIM 朋友圈',
					avatar: 'https://cdn.quasar.dev/img/avatar.png',
					type: ImEnum.OtherEnum.USER_TYPE.GROUP,
					unReadCount: 1,
					lastChatTime: '10:22',
					lastChatContent: "你好啊，傻逼",
				}]
					store.dispatch(ImEnum.DataKeyEnum.CHAT_LIST, chatroom)
			} else {

			}

		

		}
	} else if (msg.command === 11) {
		let time = new Date()
		let temp = {
			inChatUserId: 'group-' + msg.data.groupId,
			msg: [{
				msgId: 1,
				sender: msg.data.from,
				sendYear: time.getFullYear(),
				sendDay: time.getMonth() + '-' + time.getDate(),
				sendTime: time.getHours() + ':' + time.getMinutes(),
				msgType: ImEnum.ImMsgTypeEnum.text,
				count: 0, //视频或音频的长度
				msgStr: msg.data.content,
				url: ''
			}]
		}
		store.dispatch(ImEnum.DataKeyEnum.addMsgDataKey, temp)
	}

}
/**
 * @param {Object} msg
 * 关闭im连接
 */
BenderIM.colseSocket = function() {
	BenderIM.socketOpen = false
	uni.closeSocket(function(res) {
		console.log('关闭连接中：' + JSON.stringify(res));
	});

}
/**
 * @param {Object} res
 * 连接关闭后调用
 */
BenderIM.onClose = function(res) {
	if (BenderIM.socketOpen) {
		console.log('断线重连');
		let token = ImStorage.getImStorageSync(ImEnum.ImStorageEnum.loginToken)
		this.BenderSdk.login(imConfig.userMock, token)
	} else {
		console.log('关闭连接成功：' + JSON.stringify(res));
	}


}
/**
 * @param {Object} res
 * 连接关闭后调用
 */
BenderIM.onError = function(res) {
	console.log('连接错误：' + JSON.stringify(res));
}



export default BenderIM
